import { useRef, useState } from "react";
import { Download, Upload, X } from "lucide-react";
import { useSnapshot } from "valtio";
import { Label } from "@radix-ui/react-label";
import { coreState } from "@/store/core";
import { Alert, AlertDescription } from "./ui/alert";
import { Button } from "./ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
import { Input } from "./ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";

export default function Setting({ open, onClose }: { open: boolean; onClose: () => void }) {
  const snapCore = useSnapshot(coreState);
  const [error, setError] = useState<string | null>(null);
  const fileInput = useRef<HTMLInputElement>(null);
  const settingsFileInput = useRef<HTMLInputElement>(null);

  const handleBackgroundChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 1024 * 1024 * 2) {
        setError("Background image must be less than 2MB");
        return;
      }
      const reader = new FileReader();
      reader.onload = (e) => {
        coreState.setBackground(e.target?.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const removeBackground = () => {
    coreState.setBackground("");
    if (fileInput.current) {
      fileInput.current.value = "";
    }
  };

  const exportSettings = () => {
    const data = JSON.stringify(coreState.settings, null, 2);
    const blob = new Blob([data], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "newtab-settings.json";
    a.click();
    URL.revokeObjectURL(url);
  };

  const importSettings = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const imported = JSON.parse(e.target?.result as string);
          coreState.setSettings(imported, true);
          setError(null);
        } catch {
          setError("Failed to parse settings file");
        }
      };
      reader.readAsText(file);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl bg-background/95 backdrop-blur-sm border border-border/50 rounded-xl shadow-xl">
        <DialogHeader>
          <DialogTitle>Settings</DialogTitle>
          <DialogDescription>Customize your new tab page appearance and data</DialogDescription>
        </DialogHeader>

        {error && (
          <Alert variant="destructive">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        <Tabs defaultValue="appearance" className="w-full">
          <TabsList className="mb-4 bg-background/80 backdrop-blur-sm border border-border/30">
            <TabsTrigger value="appearance">外观</TabsTrigger>
            <TabsTrigger value="import">数据导入</TabsTrigger>
            <TabsTrigger value="export">数据导出</TabsTrigger>
          </TabsList>

          <TabsContent value="appearance">
            <div className="grid gap-8 [&>*]:space-y-4 p-6">
              <div>
                <Label>Background Image</Label>
                <div className="flex gap-2 items-center">
                  <Input type="file" accept="image/*" ref={fileInput} onChange={handleBackgroundChange} />
                  {snapCore.settings.background && (
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={removeBackground}
                      title="Remove background"
                      className="hover:bg-destructive/10 hover:text-destructive"
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  )}
                </div>
                {snapCore.settings.background && (
                  <div className="mt-2 relative h-32 rounded-lg overflow-hidden">
                    <img
                      src={snapCore.settings.background}
                      alt="Background preview"
                      className="w-full h-full object-cover"
                    />
                  </div>
                )}
              </div>
            </div>
          </TabsContent>

          <TabsContent value="import">
            <div className="space-y-4">
              <div>
                <Label>Import Settings</Label>
                <div className="flex gap-2 items-center">
                  <Input type="file" accept=".json" ref={settingsFileInput} onChange={importSettings} />
                  <Button
                    variant="outline"
                    onClick={() => settingsFileInput.current?.click()}
                    className="hover:bg-primary/10 hover:text-primary hover:border-primary/30"
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    Import
                  </Button>
                </div>
                <p className="text-sm text-muted-foreground mt-2">导入之前导出的JSON设置文件</p>
              </div>
            </div>
          </TabsContent>

          <TabsContent value="export">
            <div className="space-y-4">
              <div>
                <Label>Export Settings</Label>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    onClick={exportSettings}
                    className="w-full hover:bg-primary/10 hover:text-primary hover:border-primary/30"
                  >
                    <Download className="h-4 w-4 mr-2" />
                    Export Settings to JSON
                  </Button>
                </div>
                <p className="text-sm text-muted-foreground mt-2">导出当前设置，包括书签和偏好设置</p>
              </div>
            </div>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
